<?php
if ( !defined('IN_SCRIPT') ) { header("Location: index.php"); exit; }  


/******************************************************\
 * Рекурсивное удаление директории (или файла)
\******************************************************/
function fn_rm($source, $delete_root = true)
{
    // Simple copy for a file
    if (is_file($source)) {
        $res = @unlink($source);
        return $res;
    }

    // Loop through the folder
    if (is_dir($source)) {
        $dir = dir($source);
        while (false !== $entry = $dir->read()) {
            // Skip pointers
            if ($entry == '.' || $entry == '..') {
                continue;
            }
             if (fn_rm($source.DS.$entry) == false) {
                return false;
            }
        }
        // Clean up
        $dir->close();
        return ($delete_root == true) ? @rmdir($source) : true;
    } else {
        return false;
    }
}


/******************************************************\
 * Добавление и обработка сообщения
 * $msg - сообщение
 * $type = 'notice'  - информационное сообщение. не влияет на работу скрипта
 * $type = 'warning' - предупреждение. не завершает работу скрипта, но может влиять на вывод
 * $type = 'error'   - завершает работу скрипта и выводит сообщение сразу.
\******************************************************/
function add_message($msg, $type = 'notice')
{
    global $messages;
    global $current_location, $index_script, $place_name, $place;
    
    $messages[] = $msg;
    
    if ($type == 'error') {
        redirect_js("$current_location/$index_script?$place_name=$place", $msg);
        exit();
    }
}

/******************************************************\
 * Валидатор полей
 *
 * $field_descr - Описание поля
 * $field_data - данные поля
 * $field_type - тип данных (email, digit, number, alpha, alpha_space, alphanumeric, alphanumeric_space, string, date)
 * $min_length
 * $max_length
 * $field_required
\******************************************************/
function field_validator($field_descr, $field_data, 
  $field_type, $min_length="", $max_length="", 
  $field_required=1) {
    /*
    Field validator:
    This is a handy function for validating the data passed to
    us from a user's <form> fields.

    Using this function we can check a certain type of data was
    passed to us (email, digit, number, etc) and that the data
    was of a certain length.
    */
    # array for storing error messages
    global $messages, $lang;
    
    # first, if no data and field is not required, just return now:
    if(!$field_data && !$field_required){ return true; }

    # initialize a flag variable - used to flag whether data is valid or not
    $field_ok=false;

    # this is the regexp for email validation:
    $email_regexp="/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|";
    $email_regexp.="(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/";

    # a hash array of "types of data" pointing to "regexps" used to validate the data:
    $data_types=array(
        "email"=>$email_regexp,   // используется
        "digit"=>"^[0-9]$",
        "number"=>"/[0-9]{0,20}/",     // используется
        "alpha"=>"^[a-zA-Z]+$",
        "name"=>"^[a-zA-Zа-яА-Я ().,-\+\&_]+$",
        "alpha_space"=>"^[a-zA-Zа-яА-Я ]+$",    
        "alphanumeric"=>"/[a-zA-Z0-9]+/",       // используется
        "city"=>"^[a-zA-Zа-яА-Я0-9 -]+$",
        "string"=>"",             // используется  
        "name_unicode"=>"/[-\p{L}\p{N} ,\.()!?:_]/u",   // используется          \p{L}  
        "date"=>"/^([0-9]{1,2})[.,]([0-9]{1,2})[.,]([0-9]{4})$/", // используется
        "phone"=>"^[0-9, ()-]+$",
        "allowed_str"=>"^[0-9a-zA-Zа-яА-Я\"!?:() .,-_]+$",
        "url"=>"^[a-zA-Z0-9_.:/-_]+$",
        "money"=>"^([0-9]{1,20})[.]{0,1}([0-9]{0,4})$"
    );
    
    # check for required fields
    if ($field_required && empty($field_data)) {
        add_message("<b>$field_descr</b> - $lang[required_field].");
        return false;
    }
    
    # if field type is a string, no need to check regexp:
    if ($field_type == "string") {
        $field_ok = true;
    } elseif($field_type == "url") {
        $field_ok = filter_var($field_data, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED);
        if(!$field_ok) add_message($lang['wrong_url']);
        return $field_ok;
    } else {
        # Check the field data against the regexp pattern:
        $field_ok = preg_match($data_types[$field_type], $field_data, $regs);        
        if(($field_type == "date") && (!$field_ok || !checkdate($regs[2],$regs[1],$regs[3]))) {
            add_message(sprintf($lang['wrong_date'], $field_descr));
            return false;
        }
    }
    
    //DONE: добавить мультиязычность в функцию
    # if field data is bad, add message:
    if (!$field_ok) {
        add_message(sprintf($lang['wrong_data'], $field_descr));
        return false;
    }
    
    # field data min length checking:
    if ($field_ok && $min_length) {
        if (fn_strlen($field_data) < $min_length) {
            add_message(sprintf($lang['wrong_min'], $field_descr, $min_length));
            return false;
        }
    }
    
    # field data max length checking:
    if ($field_ok && $max_length) {
        if (fn_strlen($field_data) > $max_length) {
            add_message(sprintf($lang['wrong_max'], $field_descr, $max_length));
            return false;
        }
    }
    return true;
}

function fn_strlen($str) {
    return preg_match_all("#(.){1,1}#sui", $str, $tmp1);
}


/******************************************************\
 * Проверка логина/пароля на соответствие с записями в БД
\******************************************************/
function check_user($value, $password = '', $by_id = false) {
    $check_by = $by_id ? 'idusers' : 'email';
    $result=db_query("SELECT * FROM users WHERE $check_by='$value'".($password == '' ? '' : " and pass='$password'"));
    
    if(mysql_num_rows($result)==1) {
        $row=mysql_fetch_array($result);
        return $row;
    }
    return false;
}                                                                                     

/******************************************************\
 * Проверка пользователя, прошедшего авторизацию
 * через другой веб-сервис
\******************************************************/
function check_external_user($ext_id) {
    $result=db_query("SELECT * FROM `users` WHERE `external_id`='$ext_id'");
    
    if(mysql_num_rows($result)==1) {
        $row=mysql_fetch_array($result);
        return $row;
    }
    return false;
    
}

/******************************************************\
 * Регистритование переменных сессии. (вход)
\******************************************************/
#function cleanMemberSession($email, $first_name, $last_name, $id, $level) { 
function cleanMemberSession($row) {

    // сохраняем выбранный до логина язык 
    $lng = '';
    if(isset($_SESSION["language"]) && $_SESSION["language"] != '')
        $lng = $_SESSION["language"];
        
    session_regenerate_id();
   # db_query("UPDATE `users` SET `last_visit` = UTC_TIMESTAMP() where `idusers` = $row[idusers]");
    $_SESSION["login"]=$row['login'];
 //   $_SESSION["password"]=$password;
    $_SESSION["id"]=$row['idusers'];
    $_SESSION["email"]=$row['email'];
    $_SESSION["first_name"]=$row['first_name'];
    $_SESSION["last_name"]=$row['last_name'];
    $_SESSION["level"]=$row['level'];
    $_SESSION["avatar"]=$row['avatar'];
    $_SESSION["avatar_thumb"]=$row['avatar_thumb'];
    $_SESSION["last_visit"]=microtime(true);
    $_SESSION["language"]= $row['language'] != '' ? $row['language'] : $lng;
    $_SESSION["loggedIn"]=true;
      
    // настройки по умолчанию
    $_SESSION["items_per_page"]= 'a';
}


/******************************************************\
 * Обнуление параметров сессии. (выход)
\******************************************************/
function flushMemberSession() {
    // сохраняем выбранный до выхода язык 
    $lng = '';
    if(isset($_SESSION["language"]) && $_SESSION["language"] != '')
        $lng = $_SESSION["language"];
        
    // выход из ВКонтакте
    setcookie(VK_APP_ID, '', 0, "/", '.'.$_SERVER['HTTP_HOST']);
/*    include_once (INCLUDE_DIR.DS.'vk'.DS.'openapi.php');
    $vk = new Auth_Vkontakte();
    $vk_auth = $vk->logout();*/
    // TODO: удалять кукисы ВКонтакте
        
    $_SESSION = array();
    session_destroy();
    
    session_regenerate_id(); 
    session_start();
    if($lng != '') $_SESSION["language"] = $lng;
    return true;
}

/******************************************************\
 * Выбор определенного параметра из строки URL
\******************************************************/
function get_param($param_name)
{
  $param_value = "";
  if(isset($_POST[$param_name]))
    $param_value = $_POST[$param_name];
  else if(isset($_GET[$param_name]))
    $param_value = $_GET[$param_name];

  return $param_value;
}

/******************************************************\
 * Определение языка пользователя
\******************************************************/
function define_language($only_allowed = true)
{
    global $language_list;
    $langs = array();
    $accept_lang = '';
    $cur_match = '';
#    $accept_locale = '';

    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        // break up string into pieces (languages and q factors)
        preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);

        if (count($lang_parse[1])) {
            // create a list like "en" => 0.8
            $langs = array_combine($lang_parse[1], $lang_parse[4]);
            
            // set default to 1 for any without q factor
            foreach ($langs as $lang => $val) {
                if ($val === '') $langs[$lang] = 1;
            }

            // sort list based on value    
            arsort($langs, SORT_NUMERIC);
        }
    }               

    // look through sorted list and use first one that matches our languages
    foreach ($langs as $lang => $val) {
        preg_match('/^\w{2}/',$lang, $matches);
        if(empty($cur_match)) 
            $cur_match =  $matches[0] ;
        if(isset($language_list[$matches[0]]) && empty($accept_lang)) 
            $accept_lang = strtolower($matches[0]);
    }    
                                
    return $only_allowed ? $language_list[$accept_lang]['translation']  : $cur_match;
}

function get_user_info()
{   $ret = array();
    $k = get_param('id');
    
    $k = preg_match("/^[0-9]{1,10}$/", $k) ? $k : '';
    if($k != '') $ret = check_user($k, '', true);
    elseif (!empty($_SESSION['id'])) {$ret = check_user($_SESSION['id'], '', true); $k = $_SESSION['id']; }
    else return false;
    if($ret === false) return false;
    
    // количество: желаний всего (T - total), актуальных(S), с предложениями(N - new proposals), одобренные(A - approved), осуществленные(P - presented)
    // предложено мною и ждут одобрения (ME_N), принято моих предложений (ME_A), осуществлено мною (ME_P)
    $result = db_query("
                        SELECT count( DISTINCT p.`idpresents` ) AS cnt, pd.`approved` 
                        FROM `presents` p, `presented` pd
                        WHERE   p.`user` =$k
                                AND p.`idpresents` = pd.`idpresent`
                                AND pd.`approved` != 'P' 
                        GROUP BY pd.`approved` 
                        UNION ALL 
                        SELECT count( p.`idpresents` ) , 'S'
                        FROM    `presents` p
                                LEFT JOIN (
                                SELECT pp.`idpresent` , sum( pp.`amount` ) AS amt
                                FROM `presented` pp
                                WHERE pp.`approved` in ('A','P')
                                GROUP BY pp.`idpresent` 
                                )pd2 ON p.`idpresents` = pd2.`idpresent` 
                        WHERE p.`user` =$k
                        AND (
                        pd2.amt IS NULL 
                        OR pd2.amt < p.`amount`)
                        UNION ALL
                        SELECT count( p.`idpresents` ) AS cnt, 'T'
                        FROM `presents` p
                        WHERE p.`user` =$k
                        UNION ALL
                        SELECT count( p.`idpresents` ) , 'P'
                        FROM    `presents` p
                                LEFT JOIN (
                                SELECT pp.`idpresent` , sum( pp.`amount` ) AS amt
                                FROM `presented` pp
                                WHERE pp.`approved` = 'P'
                                GROUP BY pp.`idpresent` 
                                )pd2 ON p.`idpresents` = pd2.`idpresent` 
                        WHERE p.`user` =$k
                        AND pd2.amt >= p.`amount`
                        UNION ALL
                        SELECT count( 1 ) , CONCAT_WS( '_', 'ME', `approved` ) 
                        FROM `presented` 
                        WHERE `user_presenter` =$k
                        GROUP BY `approved`                        
                        " );

    while ($row = mysql_fetch_array($result)) {
        $ret[$row['approved']] = $row['cnt'];
    }
    return $ret;
                                 
}
  /*
function get_gift() {
    $gift = get_param('prid');
    if(preg_match("/^[0-9]{1,10}$/", $gift)) {
        $result = db_query("SELECT * FROM `presents` WHERE `idpresents`=".$gift);     
        if(mysql_num_rows($result)==1) {
            $row=mysql_fetch_array($result);
            return $row;        
        }
    }                                           
    return false; 
}*/

function get_gifts($one = true, $sel_option = '') {
    global $current_user, $page, $per_page, $current_gift;
    $res = array();
    
    if($one && preg_match("/^[0-9]{1,10}$/", get_param('prid')) && $current_user) {
        $where = "p.`idpresents` = ".get_param('prid')." and p.`user` = ".$current_user;
    } elseif(!$one && $current_user !== false ) {
        // определение номера страницы, на которой расположено желание
        if(empty($sel_option) && !empty($current_gift['idpresents'])) {
            db_query("SET @pos:=0");
            $result = db_query("SELECT position FROM (SELECT *, @pos:=@pos+1 as position FROM `presents` WHERE `user` =0$current_user ORDER BY `date_add` DESC) as positioned WHERE idpresents = 0".$current_gift['idpresents']);
            $row = mysql_fetch_array($result);
            $page = ceil($row['position']/$per_page); 
        }
        $where = "p.`user` =$current_user $sel_option ORDER BY p.`date_add` DESC LIMIT ".abs(($page-1)*$per_page).",$per_page";
    } else return false;
            
    $result = db_query("SELECT SQL_CALC_FOUND_ROWS p. * , e.name AS ev_name, e.date AS ev_date, 
                               gived.amount_total as gived_total, gived.amount_proposed, gived.amount_accepted, gived.amount_approved, gived.amount_presented, 
                               IF (gived.amount_accepted IS NULL , p.`amount` , p.`amount` - gived.amount_accepted) AS amount_left,
                               mygift.`approved` as mygift_approved, mygift.`amount` as mygift_amount,
                               gived.amount_total - gived.amount_accepted as amount_wait,
                               gived.total_users
                        FROM `presents` p
                        LEFT JOIN `events` e ON e.`idevents` = p.`idevent` 
                        LEFT JOIN (SELECT `idpresent` , sum( `amount` ) AS amount_total, 
                                          sum(IF (`approved` IS NOT NULL AND `approved` != 'N', `amount` , 0) ) AS amount_accepted, 
                                          sum(IF (`approved` = 'N', `amount` , 0) ) AS amount_proposed, 
                                          sum(IF (`approved` = 'A', `amount` , 0) ) AS amount_approved, 
                                          sum(IF (`approved` = 'P', `amount` , 0) ) AS amount_presented,
                                          count( DISTINCT `user_presenter` ) AS total_users "./*, 
                                          sum(IF (`user_presenter` =10 AND `approved` = 'N', `amount` , 0) ) AS my_amount_proposed, 
                                          sum(IF (`user_presenter` =10 AND `approved` = 'P', `amount` , 0) ) AS my_amount_presented  */
                                   "FROM presented
                                   GROUP BY `idpresent`) gived ON gived.`idpresent` = p.idpresents
                        LEFT JOIN (SELECT `idpresent` , `approved` , `amount` 
                                   FROM `presented` 
                                   WHERE `user_presenter` =".(LOGGED_IN ? $_SESSION['id'] : -100).") mygift on mygift.`idpresent` = p.idpresents
                        WHERE ".$where);

    while ($row = mysql_fetch_array($result)) {
        $res[$row['idpresents']] = $row;
        $res[$row['idpresents']]['ev_date'] = format_date_out($row['ev_date'], true);
        $res[$row['idpresents']]['short_name'] = ShortenText($res[$row['idpresents']]['name'], 40);
        $res[$row['idpresents']]['short_link'] = ShortenText($res[$row['idpresents']]['link'], 30, false);
        if($one) return $res[$row['idpresents']];
        
    }
  //  if($one) {header("Location: index.php"); exit; }
    $result=db_query("SELECT FOUND_ROWS()");
    $row = mysql_fetch_array($result);  // количество подарков всего
    $res['total_rows'] = $row[0];
    return $one ? false : $res;
}

function get_iwish($sel_option) {
    global $page, $per_page;
    $res = array();
    
    $result = db_query("SELECT SQL_CALC_FOUND_ROWS p.*, pr.*, e.`name` as ev_name, e.`date` as ev_date, u.`idusers`, u.`login`, u.`first_name`, u.`last_name`, u.`last_visit`, u.`reg_date`
                        FROM `presented` pr, `users` u,`presents` p left join `events` e on p.`idevent` = e.`idevents`
                        WHERE pr.`idpresent` = p.`idpresents` AND p.`user` = u.`idusers` AND pr.`user_presenter` =0".$_SESSION['id']." $sel_option
                        LIMIT ".abs(($page-1)*$per_page).",$per_page");
    while ($row = mysql_fetch_array($result)) {
        $res[$row['idpresents']] = $row;
        $res[$row['idpresents']]['ev_date'] = format_date_out($row['ev_date'], true);
        $res[$row['idpresents']]['short_name'] = ShortenText($res[$row['idpresents']]['name'], 40);
        $res[$row['idpresents']]['short_link'] = ShortenText($res[$row['idpresents']]['link'], 30, false);
    }
    $result=db_query("SELECT FOUND_ROWS()");
    $row = mysql_fetch_array($result);  // количество подарков всего
    $res['total_rows'] = $row[0];
    
    return $res; 
}


/******************************************************\
 * Статистика по сайту
\******************************************************/
function get_overall_stats() {
    $res = array();
    $result = db_query("SELECT count(p.`idpresents`) as cnt_total, count(pr.`idpresent`) as cnt_done, count(if(pr2.`idpresent` is null, 1, null )) as cnt_new
                        FROM `presents` p
                        left join (select distinct `idpresent` from `presented` where `approved`='P') pr on pr.`idpresent` = p.`idpresents`
                        left join (select distinct `idpresent` from `presented` where `idpresent` is not null) pr2 on pr2.`idpresent` = p.`idpresents`");
    $res = mysql_fetch_array($result);
    return $res;
}

/******************************************************\
 * Форматирование даты для вывода пользователю
\******************************************************/
function format_date_out($utc_date, $static = false) {
    global $current_time_offset, $lang;
    $utc_time = strtotime($utc_date);      // UTC время
    $t = time();  // локальное текущее время СЕРВЕРА  
    $user_current_time = $t-date("Z",$t) + $current_time_offset;
    $user_time = $utc_time + $current_time_offset;      
    $delta = $user_current_time - $user_time;         
    
    if(empty($utc_date) || !($utc_date > 0))
        return '';
        
    if($delta < 0 || $static)  // будущая дата
        return strftime("%x", $user_time);
    elseif($delta < 60)   // Х секунд назад
        return sprintf($lang['x_sec_ago'], $delta);
    elseif($delta < 3600) // Х минут назад
        return sprintf($lang['x_min_ago'], round($delta/60));
    elseif(strftime("%x", $user_current_time) == strftime("%x", $user_time) )     // Х часов Y минут назад (если сегодня)
        return sprintf($lang['x_hr_y_min_ago'], floor($delta/3600), round(($delta - floor($delta/3600)*3600)/60));
    elseif(strftime("%x", $user_current_time) == strftime("%x", $user_time + 24*3600) )     // вчера
        return $lang['yesterday'].', '.strftime("%H:%M", $user_time);
    else
        return strftime("%x", $user_time);
}

function get_link($link_hash) {
    if (preg_match("/[0-9a-z\.]/", $link_hash)) {
        $result = db_query("SELECT * FROM `presents` WHERE `link_hash`='$link_hash'");
        if(mysql_num_rows($result)==1) {
            $row=mysql_fetch_array($result);
            return $row;
        }
    }
    return false;
}

function fn_mail($to, $subject, $body, $from_address = '', $from_name = '', $alt_body = '') {
    require_once(INCLUDE_DIR.DS.'mailer.php');
    global $main_host;

    $mail = new PHPMailerLite(true); // the true param means it will throw exceptions on errors, which we need to catch
    #$mail->IsSendmail(); // telling the class to use SendMail transport
    $mail->IsMail(); // telling the class to use native PHP mail()
    
    if(!$from_address) $from_address = "no-reply@$main_host";
    if(!$from_name) $from_name = $main_host;                

    try {
        $mail->SetFrom($from_address, $from_name);
        if(is_array($to)) 
            foreach ($to as $m) $mail->AddAddress($m);
        else
            $mail->AddAddress($to);
        if (!$alt_body){
            $alt_body = strip_tags($body);
        }
            
        $mail->Subject = $subject;
        $mail->AltBody = $alt_body; // optional - MsgHTML will create an alternate automatically
        $mail->MsgHTML($body);
        $mail->CharSet = 'utf-8';
         # $mail->AddAttachment('images/phpmailer.gif');      // attachment
         # $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
        $mail->Send();
        return true;
    } catch (phpmailerException $e) {
        #echo $e->errorMessage(); //Pretty error messages from PHPMailer
        return $e->errorMessage();
    } /*catch (Exception $e) {
      echo $e->getMessage(); //Boring error messages from anything else!
    }               */
    return false;
}

function date_from_db($format, $date) {
    global $current_time_offset;
    return strftime($format, strtotime($date) + $current_time_offset);
}
/*
function date_to_db($timestamp = '') {
    global $current_time_offset;
    if($timestamp == '') $ts = time();

    return date("Y-m-d H:i:s", $ts);
} */
    /*
function GetRealIp()
{
 if (!empty($_SERVER['HTTP_CLIENT_IP'])) 
 {
   $ip=$_SERVER['HTTP_CLIENT_IP'];
 }
 elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
 {
  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
 }
 else
 {
   $ip=$_SERVER['REMOTE_ADDR'];
 }
 return $ip;
}
          */
function GetRealIp($return_int = false)
{
    $forwarded_ip = '';
    $fields = array(
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'HTTP_forwarded_ip',
        'HTTP_X_COMING_FROM',
        'HTTP_COMING_FROM',
        'HTTP_CLIENT_IP',
        'HTTP_VIA',
        'HTTP_XROXY_CONNECTION',
        'HTTP_PROXY_CONNECTION');

    $matches = array();
    foreach ($fields as $f) {
        if (!empty($_SERVER[$f])) {
            preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $_SERVER[$f], $matches);
            if (!empty($matches) && !empty($matches[0]) && $matches[0] != $_SERVER['REMOTE_ADDR']) {
                $forwarded_ip = $matches[0];
                break;
            }
        }
    }

    $ip = array('host' => $forwarded_ip, 'proxy' => $_SERVER['REMOTE_ADDR']);
    
    if ($return_int) {
        foreach ($ip as $k => $_ip) {
            $ip[$k] = empty($_ip) ? 0 : sprintf("%u", ip2long($_ip));
        }
    }
    
    if (empty($ip['host'])) {
        $ip['host'] = $ip['proxy'];
        $ip['proxy'] = $return_int ? 0 : '';
    }
 /*   
    $ip_num = '';
    if (!empty($ip['host']) && fn_is_inet_ip($ip['host'])) {
        $ip_num = $ip['host'];
    } elseif (!empty($ip['proxy']) && fn_is_inet_ip($ip['proxy'])) {
        $ip_num = $ip['proxy'];
    }
        */
    return $ip;
}

//
// If there is IP address in address scope global then return true.
//
function fn_is_inet_ip($ip, $is_int = false)
{
    if ($is_int) {
        $ip = long2ip($ip);
    }
    $_ip = explode('.', $ip);
    return 
        ($_ip[0] == 10 || 
        ($_ip[0] == 172 && $_ip[1] >= 16 && $_ip[1] <= 31) || 
        ($_ip[0] == 192 && $_ip[1] == 168) || 
        ($_ip[0] == 127 && $_ip[1] == 0 && $_ip[2] == 0 && $_ip[3] == 1) ||
        ($_ip[0] == 255 && $_ip[1] == 255 && $_ip[2] == 255 && $_ip[3] == 255))
        ? false : true;
}

function fn_log($comment = '') {
    global $current_location;
    global $index_script;
    global $place_name, $mode_name;
    global $place, $mode;
    
    $exp = fopen("out.txt", "a");
    $dat = array();
    $dat['time'] = date("d.m.Y H:i:s");
    $ip = GetRealIp();
    $dat['ip'] = $ip['host'].(!empty($ip['proxy']) ? " ($ip[proxy])" : '');
    $dat['logged_user'] = isset($_SESSION['id'])  ? $_SESSION['id'] : 'GUEST';
    $dat['current_user'] = get_param('id');
    $dat['current_gift'] = get_param('prid');
    $dat['location'] = $current_location.'/'.$index_script.($place ? "?$place_name=$place".($mode ? "&$mode_name=$mode" : '') : '');
  #  $dat['php_self'] = $_SERVER['PHP_SELF'];
    $dat['query'] = $_SERVER['QUERY_STRING'];
    $dat['URI'] = $_SERVER['REQUEST_URI'];
    $dat['browser'] = $_SERVER['HTTP_USER_AGENT'];
    $dat['get_or_post'] = $_SERVER['REQUEST_METHOD'];
    $dat['ajax_request'] = get_param('ajax') == 'yes' ? 'YES' : 'NO';
    $dat['comment'] = $comment;
    
  #  fwrite($exp, implode("\t", array_keys($dat) )."\n");
    fwrite($exp, implode("^", $dat)."\n");
    fclose($exp);
}

function fn_stat() {
    global $start_time, $page_title, $current_location,
           $place, $mode,
           $place_name, $mode_name,
           $uniq_session;
          
  #  if(isset($_GET['ajax']) && $_GET['ajax'] == 'yes') return false;
    
    $dat = array();
    $dat['time'] = gmdate("Y-m-d H:i:s");        //  текущее время по гринвичу
    $ip = GetRealIp();     
    $dat['ip'] = $ip['host'].(!empty($ip['proxy']) ? " ($ip[proxy])" : '');
    $dat['host'] = ''; //gethostbyaddr($ip['host']); # пока отключил - очень тормозит определение хоста
    $dat['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
    if(isset($_SESSION['id'])) $dat['logged_user'] = $_SESSION['id'];
    $dat['title'] = $page_title;
    $dat['load_time'] = microtime(true) - $start_time;
    $lng = define_language(false); 
    $dat['language'] = (isset($_SESSION['language']) && $_SESSION['language'] != $lng) ? "$lng ($_SESSION[language])" : $lng;
    $loc = empty($_SERVER['QUERY_STRING']) ? ($place ? "id=".get_param('id')."&$place_name=$place".($mode ? "&$mode_name=$mode" : '') : '') : $_SERVER['QUERY_STRING'];
    $dat['url'] = $current_location.($loc != '' ? $_SERVER['SCRIPT_NAME']."?".$loc : '/');
    $dat['refferer'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
    $dat['session'] = $uniq_session;
    preg_match("~([^/[:space:]]*)(/([^[:space:]]*))?([[:space:]]*\[[a-zA-Z][a-zA-Z]\])?[[:space:]]*(\\((([^()]|(\\([^()]*\\)))*)\\))?[[:space:]]~", $_SERVER['HTTP_USER_AGENT'], $matches);
    $dat['browser'] = $matches[1];
    $dat['request'] = get_param('ajax') == 'yes' ? 'AJAX' : ($place == 'out' ? 'OUT' : $_SERVER['REQUEST_METHOD']);    
    
    $record_id = db_insert($dat, true, 'stats');
    return $record_id; 
}

function ShortenText($input, $chars, $by_words = true, $enc = 'utf-8') {
    if(mb_strlen($input, $enc) > $chars) {  
        $text = mb_substr($input,0,$chars, $enc); 
        if($by_words)
            $text = mb_substr($text,0,mb_strrpos($text,' ', 0, $enc), $enc); 
        $text = $text." ..."; 
        return $text; 
    }
    return $input;
}


function fn_load_settings() {
    if(!LOGGED_IN) return false;
    
  /*  $result=db_query("SELECT `setting_more_gifts` FROM `users` WHERE `idusers`=".$_SESSION['id']);
    
    if(mysql_num_rows($result)!=1) return false; 

    $row=mysql_fetch_array($result);
    return $row;       */
    
    return false;
}
    
    
//DONE: валидацию ссылок поправить
//DONE 3: выводить ссылки через редирект (сделать отдельную таблицу, вести подсчет кликов) 
//DONE 3: логировать ошибки 
//TODO 1: выбор часовой зоны (пользователем)
//DONE 2: добавить подсказки
//TODO 1: добавить добавление в друзья
//DONE 2: при переключении языка учитывать ЧПУ
//DONE 5: обрабатывать ошибки перед отправкой формы через аякс

/* DONE 5: статистика
* + количество просмотров страниц (в том числе, уникальных)
* кол-во переходов на другие сайты  
* кол-во переходов с внешних (реферальных) ссылок                               
* кол-во показов внешних ссылок (картинок, фреймов, джава-скриптов)
*/

?>
